package com.wingscode.modules.app.controller;

import com.wingscode.common.utils.R;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import static com.wingscode.modules.file.config.WebConfig.FILEPATH;


/**
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2019-05-07 17:50:21
 */
@RestController
@RequestMapping("app/file")
@Api("文件")
public class AppFileController {
    /**
     * 上传文件
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public R upload(@RequestParam("file") MultipartFile[] files) throws IOException {
        if (files.length < 1) {
            return R.error("文件不能为空");
        }
        List<String> fileNameList=new ArrayList<>();
        for(MultipartFile file:files){
            String fileName = file.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            if (suffixName.equals(".png") || suffixName.equals(".jpg") || suffixName.equals(".jpeg")) {
            } else {
                return R.error("不支持该格式");
            }
            fileName = UUID.randomUUID() + suffixName;
            File dest = new File(FILEPATH + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest.getAbsoluteFile());
            fileNameList.add(fileName);
        }
        return R.ok(200, fileNameList);
    }
}
